import tkinter as tk
from tkinter import messagebox, simpledialog
import threading
import time
import datetime
import os
import sys

# 跨平台声音提醒函数
def play_alarm_sound():
    try:
        if sys.platform.startswith('win'):
            import winsound
            winsound.Beep(1000, 1000)  # 频率1000Hz，持续1秒
        elif sys.platform.startswith('darwin'):  # macOS
            os.system('afplay /System/Library/Sounds/Glass.aiff')
        else:  # Linux
            os.system('beep -f 1000 -l 1000 2>/dev/null || paplay /usr/share/sounds/gnome/default/alerts/glass.ogg 2>/dev/null')
    except Exception as e:
        print("播放声音失败:", e)

# 闹钟线程类
class AlarmClock:
    def __init__(self, gui):
        self.gui = gui
        self.running = True
        self.thread = threading.Thread(target=self.check_alarms, daemon=True)
        self.thread.start()

    def check_alarms(self):
        while self.running:
            now = datetime.datetime.now()
            current_time_str = now.strftime("%H:%M")
            current_minute = now.minute

            # 检查固定时间闹钟
            for alarm in self.gui.alarms[:]:
                if alarm['type'] == 'fixed' and alarm['time'] == current_time_str and not alarm.get('triggered_today', False):
                    self.trigger_alarm(alarm)
                    alarm['triggered_today'] = True  # 今天已触发，避免重复

            # 检查每小时分钟闹钟
            for alarm in self.gui.alarms[:]:
                if alarm['type'] == 'hourly' and alarm['minute'] == current_minute:
                    # 避免一分钟内重复触发（可选加 last_triggered 时间戳）
                    self.trigger_alarm(alarm)

            # 每天重置 fixed 闹钟的触发状态
            if now.hour == 0 and now.minute == 0:
                for alarm in self.gui.alarms:
                    if alarm['type'] == 'fixed':
                        alarm['triggered_today'] = False

            time.sleep(30)  # 每30秒检查一次，避免过于频繁

    def trigger_alarm(self, alarm):
        def show_alert():
            play_alarm_sound()
            msg = f"⏰ 闹钟响了！\n"
            messagebox.showinfo("闹钟提醒", msg)
        # 在主线程中弹窗（线程安全）
        self.gui.root.after(0, show_alert)

    def stop(self):
        self.running = False

# 主GUI类
class AlarmGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("⏰ 桌面闹钟")
        self.root.geometry("500x400")
        self.root.resizable(False, False)

        self.alarms = []  # 存储闹钟列表

        # 标题
        tk.Label(root, text="我的闹钟列表", font=("Arial", 16)).pack(pady=10)

        # 闹钟列表框
        self.listbox = tk.Listbox(root, width=50, height=12, font=("Arial", 12))
        self.listbox.pack(pady=10)

        # 按钮框架
        btn_frame = tk.Frame(root)
        btn_frame.pack(pady=10)

        tk.Button(btn_frame, text="添加固定时间闹钟", command=self.add_fixed_alarm).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="添加每小时分钟闹钟", command=self.add_hourly_alarm).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="删除选中闹钟", command=self.delete_alarm).pack(side=tk.LEFT, padx=5)

        # 启动闹钟线程
        self.alarm_clock = AlarmClock(self)

        # 窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    def add_fixed_alarm(self):
        time_str = simpledialog.askstring("添加闹钟", "请输入时间 (HH:MM 格式):")
        if time_str:
            try:
                datetime.datetime.strptime(time_str, "%H:%M")
                alarm = {'type': 'fixed', 'time': time_str, 'triggered_today': False}
                self.alarms.append(alarm)
                self.update_listbox()
            except ValueError:
                messagebox.showerror("错误", "时间格式错误，请输入 HH:MM 格式")

    def add_hourly_alarm(self):
        minute_str = simpledialog.askstring("添加每小时闹钟", "请输入分钟数 (0-59):")
        if minute_str and minute_str.isdigit():
            minute = int(minute_str)
            if 0 <= minute <= 59:
                alarm = {'type': 'hourly', 'minute': minute}
                self.alarms.append(alarm)
                self.update_listbox()
            else:
                messagebox.showerror("错误", "分钟数必须在 0-59 之间")
        else:
            messagebox.showerror("错误", "请输入有效数字")

    def delete_alarm(self):
        selected = self.listbox.curselection()
        if selected:
            idx = selected[0]
            del self.alarms[idx]
            self.update_listbox()
        else:
            messagebox.showwarning("提示", "请先选中一个闹钟")

    def update_listbox(self):
        self.listbox.delete(0, tk.END)
        for alarm in self.alarms:
            if alarm['type'] == 'fixed':
                self.listbox.insert(tk.END, f"🕒 固定时间: {alarm['time']}")
            else:
                self.listbox.insert(tk.END, f"⏱️ 每小时第 {alarm['minute']} 分钟")

    def on_closing(self):
        if messagebox.askokcancel("退出", "确定要退出闹钟程序吗？"):
            self.alarm_clock.stop()
            self.root.destroy()

# 主程序入口
if __name__ == "__main__":
    root = tk.Tk()
    app = AlarmGUI(root)
    root.mainloop()
